import config from './config.js'

function shake(callback) {
  // 摇一摇
  var lastX = 0,
    lastY = 0,
    lastZ = 0;
  wx.onAccelerometerChange(function(res) {
    if (lastX) {
      var deltaX = Math.abs(res.x - lastX),
        deltaY = Math.abs(res.y - lastY),
        deltaZ = Math.abs(res.z - lastZ);
      if (deltaX > 0.9 || deltaY > 0.9 || deltaZ > 0.9) {
        callback();
      }
    }
    lastX = res.x;
    lastY = res.y;
    lastZ = res.z;
  })
}
/**
 * 微信登录
 */
const login = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: res => {
        let {
          code
        } = res
        resolve(code)
      }
    })
  })
}


/**
 * http 请求
 */
const http = (url, data, auth = true, method = 'POST') => {
  let header = {
    "content-type": "application/x-www-form-urlencoded"
  }
  
  if (auth) {
    let user_login = wx.getStorageSync('user_login')
    header["token"] = user_login.system_token
  }
  return new Promise((resolve, reject) => {
    // wx.showLoading({
    //   title: '加载中...',
    // })
    wx.request({
      url: config.http + url,
      data: data,
      method: method,
      header: header,
      success: function(res) {
        wx.hideLoading()
        resolve(res.data)
      },
      fail: function(res) {
        reject(res)
      }
    })
  })
}

/**
 * 身份验证
 */
const auth = () => {
  let url = '/tokenVerify'
  let user_login = wx.getStorageSync('user_login')
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success: function() {
        http(url).then(res => {
          if (res.code == 1) {
            resolve(true)
          } else {
            wx.showToast({
              title: "token已过期，请到我的页面授权登录",
              icon: 'none',
            })
            wx.removeStorageSync('user_login')
            resolve(false)
          }
        })
      },
      fail: function() {
        wx.showToast({
          title: "您未授权登录，请到我的页面授权登录",
          icon: 'none',
        })
        resolve(false)
      }
    })
  })
}



module.exports = {
  shake: shake,
  login: login,
  auth: auth,
  http: http
}